/*
 * Copyright (c) 2020 - present, Inspur Genersoft Co., Ltd.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package io.iec.edp.caf.commons;


import io.iec.edp.caf.commons.wrapper.ProtobufWrapper;
import io.iec.edp.caf.commons.wrapper.ProtobufWrapperUtils;
import io.protostuff.*;
import io.protostuff.runtime.RuntimeSchema;

/**
 * Protobuf工具
 */
class ProtobufUtils {

    public static <T> byte[] serialize(T obj) {
        byte[] ret = new byte[0];
        LinkedBuffer buffer = LinkedBuffer.allocate(LinkedBuffer.DEFAULT_BUFFER_SIZE);
        try {
            if (obj == null || ProtobufWrapperUtils.needWrapper(obj)) {
                Schema<ProtobufWrapper> schema = RuntimeSchema.getSchema(ProtobufWrapper.class);
                ProtobufWrapper wrapper = new ProtobufWrapper(obj);
                ret = ProtobufIOUtil.toByteArray(wrapper, schema, buffer);
            } else {
                Schema schema = RuntimeSchema.getSchema(obj.getClass());
                ret = ProtobufIOUtil.toByteArray(obj, schema, buffer);
            }
            return ret;

        } catch (Exception e) {
            throw e;
        } finally {
            buffer.clear();
        }
    }


    public static <T> T deserialize(byte[] data, Class<T> clazz) {
        Object result;
        try {
            if (ProtobufWrapperUtils.needWrapper(clazz)) {
                Schema<ProtobufWrapper> schema = RuntimeSchema.getSchema(ProtobufWrapper.class);
                ProtobufWrapper wrapper = schema.newMessage();
                ProtobufIOUtil.mergeFrom(data, wrapper, schema);
                result = wrapper.getData();
            } else {
                Schema schema = RuntimeSchema.getSchema(clazz);
                result = schema.newMessage();
                ProtobufIOUtil.mergeFrom(data, result, schema);
            }

            return (T)result;

        } catch (Exception e) {
            throw e;
        }
    }

}
